<template>
  <div class="procurement-orders">
    <!-- 页面标题 -->
    <PageHeader 
      title="采购订单" 
      description="管理采购订单，包括订单创建、审批、执行等"
      icon="Document"
    />
    
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="订单编号">
          <el-input v-model="filterForm.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="filterForm.supplier" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审批" value="pending" />
            <el-option label="已审批" value="approved" />
            <el-option label="采购中" value="purchasing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleCreateOrder">创建订单</el-button>
      <el-button @click="handleImport">导入订单</el-button>
      <el-button @click="handleExport">导出订单</el-button>
    </div>
    
    <!-- 订单列表 -->
    <el-card class="list-card" shadow="never">
      <el-table :data="orderList" style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNo" label="订单编号" width="150" />
        <el-table-column prop="supplierName" label="供应商" min-width="150" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column prop="expectedDeliveryDate" label="预计到货时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="success" link @click="handleEdit(row)" v-if="row.status === 'pending'">编辑</el-button>
            <el-button type="warning" link @click="handleApprove(row)" v-if="row.status === 'pending'">审批</el-button>
            <el-button type="danger" link @click="handleCancel(row)" v-if="['pending', 'approved', 'purchasing'].includes(row.status)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 订单对话框 -->
    <el-dialog v-model="orderDialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="orderForm" label-width="100px" ref="orderFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" required>
              <el-select v-model="orderForm.supplierId" placeholder="请选择供应商" filterable>
                <el-option
                  v-for="supplier in supplierOptions"
                  :key="supplier.id"
                  :label="supplier.name"
                  :value="supplier.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计到货时间" required>
              <el-date-picker
                v-model="orderForm.expectedDeliveryDate"
                type="date"
                placeholder="请选择预计到货时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注">
          <el-input v-model="orderForm.remark" type="textarea" />
        </el-form-item>
        
        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <el-table :data="orderForm.items" style="width: 100%">
            <el-table-column prop="productName" label="商品名称" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.productName" placeholder="请输入商品名称" />
              </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格" width="120">
              <template #default="{ row }">
                <el-input v-model="row.specification" placeholder="请输入规格" />
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="1" />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.unitPrice" :min="0" :precision="2" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{ row }">
                ¥{{ (row.quantity * row.unitPrice).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button type="danger" link @click="removeOrderItem($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="addOrderItem">添加商品</el-button>
          </div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总金额">
              <el-input v-model="totalAmount" disabled>
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmOrder">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from '@vue/runtime-core'
import PageHeader from '@/components/layout/PageHeader.vue'

// 数据模型
interface OrderItem {
  id: number
  productName: string
  specification: string
  quantity: number
  unitPrice: number
}

interface Order {
  id: number
  orderNo: string
  supplierId: number
  supplierName: string
  totalAmount: number
  status: 'pending' | 'approved' | 'purchasing' | 'completed' | 'cancelled'
  creator: string
  createdAt: string
  expectedDeliveryDate: string
  remark: string
  items: OrderItem[]
}

interface Supplier {
  id: number
  name: string
}

// 筛选表单
const filterForm = reactive({
  orderNo: '',
  supplier: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 状态
const loading = ref(false)
const orderList = ref<Order[]>([])
const orderDialogVisible = ref(false)
const dialogTitle = ref('创建订单')
const isEdit = ref(false)

// 表单引用
const orderFormRef = ref()

// 表单数据
const orderForm = reactive({
  id: 0,
  supplierId: 0,
  expectedDeliveryDate: '',
  remark: '',
  items: [] as OrderItem[]
})

// 供应商选项
const supplierOptions = ref<Supplier[]>([
  { id: 1, name: '华为技术有限公司' },
  { id: 2, name: '阿里巴巴集团' },
  { id: 3, name: '小米科技有限公司' }
])

// 计算总金额
const totalAmount = computed(() => {
  return orderForm.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0)
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'approved': return 'primary'
    case 'purchasing': return 'info'
    case 'completed': return 'success'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待审批'
    case 'approved': return '已审批'
    case 'purchasing': return '采购中'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知'
  }
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', filterForm)
  loadOrderList()
}

// 重置
const handleReset = () => {
  filterForm.orderNo = ''
  filterForm.supplier = ''
  filterForm.status = ''
  loadOrderList()
}

// 加载订单列表
const loadOrderList = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    orderList.value = [
      {
        id: 1,
        orderNo: 'PO20251115001',
        supplierId: 1,
        supplierName: '华为技术有限公司',
        totalAmount: 1250000,
        status: 'approved',
        creator: '张三',
        createdAt: '2025-11-15 09:30:00',
        expectedDeliveryDate: '2025-11-25',
        remark: '紧急订单',
        items: [
          { id: 1, productName: '服务器', specification: '2U机架式', quantity: 10, unitPrice: 85000 },
          { id: 2, productName: '交换机', specification: '24口千兆', quantity: 20, unitPrice: 20000 }
        ]
      },
      {
        id: 2,
        orderNo: 'PO20251115002',
        supplierId: 2,
        supplierName: '阿里巴巴集团',
        totalAmount: 850000,
        status: 'pending',
        creator: '李四',
        createdAt: '2025-11-15 14:20:30',
        expectedDeliveryDate: '2025-11-30',
        remark: '常规采购',
        items: [
          { id: 1, productName: '云服务器', specification: 'ECS实例', quantity: 50, unitPrice: 17000 }
        ]
      }
    ]
    pagination.total = 50
    loading.value = false
  }, 500)
}

// 操作按钮
const handleCreateOrder = () => {
  dialogTitle.value = '创建订单'
  isEdit.value = false
  resetOrderForm()
  orderDialogVisible.value = true
}

const handleImport = () => {
  console.log('导入订单')
}

const handleExport = () => {
  console.log('导出订单')
}

// 查看订单
const handleView = (row: Order) => {
  console.log('查看订单:', row)
}

// 编辑订单
const handleEdit = (row: Order) => {
  dialogTitle.value = '编辑订单'
  isEdit.value = true
  Object.assign(orderForm, row)
  orderDialogVisible.value = true
}

// 审批订单
const handleApprove = (row: Order) => {
  console.log('审批订单:', row)
  loadOrderList()
}

// 取消订单
const handleCancel = (row: Order) => {
  console.log('取消订单:', row)
  loadOrderList()
}

// 重置表单
const resetOrderForm = () => {
  orderForm.id = 0
  orderForm.supplierId = 0
  orderForm.expectedDeliveryDate = ''
  orderForm.remark = ''
  orderForm.items = []
  addOrderItem()
}

// 添加订单项
const addOrderItem = () => {
  orderForm.items.push({
    id: 0,
    productName: '',
    specification: '',
    quantity: 1,
    unitPrice: 0
  })
}

// 删除订单项
const removeOrderItem = (index: number) => {
  orderForm.items.splice(index, 1)
}

// 确认订单操作
const confirmOrder = () => {
  console.log('确认订单操作:', orderForm)
  orderDialogVisible.value = false
  loadOrderList()
}

// 分页操作
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadOrderList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadOrderList()
}

// 生命周期
onMounted(() => {
  loadOrderList()
})
</script>

<style scoped>
.procurement-orders {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.list-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>